import 'package:dio/dio.dart';
import 'package:enjoy_plus_three/utils/eventbus.dart';
import 'package:enjoy_plus_three/utils/http.dart';
import 'package:enjoy_plus_three/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});
  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {'avatar': null, 'nickName': null};

  final TextEditingController _avatarController = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _avatarController.text = userInfo['nickName'];
    });
  }

  // 修改昵称
  updateNickName() async {
    if (_avatarController.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    try {
      await http.put('/userInfo', {"nickName": _avatarController.text});
      setState(() {
        userInfo['nickName'] = _avatarController.text;
        ToastUtil.showSuccess('修改成功!');
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
  }

  // 从相机或相册中选择图片
  selectAvatar() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SizedBox(
          height: 200,
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                onTap: () {
                  uploadAvator('camera');
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo),
                title: const Text('相册'),
                onTap: () {
                  uploadAvator('gallery');
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> uploadAvator(String imageType) async {
    final ImagePicker picker = ImagePicker();
    if (imageType == 'camera') {
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      if (photo != null) {
        ToastUtil.showSuccess(photo.path);
        print('imagePath:${photo.path}');
        try {
          FormData formData = FormData.fromMap({
            "file": await MultipartFile.fromFile(photo.path),
            "type": "avatar",
          });
          var res = await http.post('/upload', formData);
          if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
          setState(() {
            userInfo['avatar'] = res['data']['url'];
          });
        } finally {
          Navigator.pop(context);
        }
      }
    } else if (imageType == 'gallery') {
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        ToastUtil.showSuccess(image.path);
        try {
          FormData formData = FormData.fromMap({
            "file": await MultipartFile.fromFile(image.path),
            "type": "avatar",
          });
          var res = await http.post('/upload', formData);
          if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
          setState(() {
            userInfo['avatar'] = res['data']['url'];
          });
        } finally {
          Navigator.pop(context);
        }
      }
    }

    // if (pickedFile != null) {
    // try {
    //   FormData formData = FormData.fromMap({
    //     "file": await MultipartFile.fromFile(pickedFile.path),
    //     "type": "avatar",
    //   });
    //   var res = await http.post('/upload', formData);
    //   if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
    //   setState(() {
    //     userInfo['avatar'] = res['data']['url'];
    //   });
    // } finally {
    //   Navigator.pop(context);
    // }
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(
          onPressed: () {
            eventBus.fire(RefreshMine());
            Navigator.pop(context);
          },
          icon: Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        selectAvatar();
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child:
                            userInfo['avatar'] != null
                                ? Image.network(widget.userInfo['avatar'])
                                : Image.asset(
                                  'assets/images/avatar_1.jpg',
                                  width: 30,
                                  height: 30,
                                ),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12),
                  ],
                ),
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  onEditingComplete: () {
                    updateNickName();
                  },
                  controller: _avatarController,
                  decoration: InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12),
            ],
          ),
        ],
      ),
    );
  }
}
